<?php
namespace SixShop\News\Controller\Admin;

use think\Request;
use think\facade\Validate;
use SixShop\News\Service\NewsServiceAdapter;
use SixShop\News\Service\NewsCategoryServiceAdapter;

class NewsController
{
    protected $service;

    public function __construct()
    {
        $this->service = new NewsServiceAdapter();
    }

    /**
     * 文章列表
     */
    public function index(Request $request)
    {
        $where = [];
        if ($request->get('category_id')) {
            $where['category_id'] = $request->get('category_id');
        }
        if ($request->get('status') !== null) {
            $where['status'] = $request->get('status');
        }
        $limit = (int)$request->get('limit', 20);
        $data = $this->service->getList($where, ['is_top'=>'desc','id'=>'desc'], $limit);
        
        // 从数据库获取分类数据
        $categoryMap = [];
        try {
            // 使用ThinkPHP的Db类查询数据库
            $categories = \think\facade\Db::table('cy_news_category')
                ->where('status', 1)
                ->whereNull('delete_time')
                ->field('id,name')
                ->select()
                ->toArray();
            
            // 构建分类映射
            foreach ($categories as $category) {
                $categoryMap[$category['id']] = $category['name'];
            }
        } catch (\Exception $e) {
            // 如果查询失败，使用默认映射
            error_log('获取分类数据失败: ' . $e->getMessage());
            $categoryMap = [
                1 => '默认分类',
                2 => '新闻分类', 
                3 => '公告分类'
            ];
        }
        
        // 字段映射：数据库cover_image -> 前端cover，添加分类名称
        if (is_array($data) && isset($data['data'])) {
            foreach ($data['data'] as &$item) {
                if (isset($item['cover_image'])) {
                    $item['cover'] = $item['cover_image'];
                }
                if (isset($item['category_id']) && isset($categoryMap[$item['category_id']])) {
                    $item['category_name'] = $categoryMap[$item['category_id']];
                }
            }
        } elseif (is_array($data) && isset($data['list'])) {
            foreach ($data['list'] as &$item) {
                if (isset($item['cover_image'])) {
                    $item['cover'] = $item['cover_image'];
                }
                if (isset($item['category_id']) && isset($categoryMap[$item['category_id']])) {
                    $item['category_name'] = $categoryMap[$item['category_id']];
                }
            }
        } elseif (is_array($data)) {
            foreach ($data as &$item) {
                if (isset($item['cover_image'])) {
                    $item['cover'] = $item['cover_image'];
                }
                if (isset($item['category_id']) && isset($categoryMap[$item['category_id']])) {
                    $item['category_name'] = $categoryMap[$item['category_id']];
                }
            }
        }
        
        return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 文章详情
     */
    public function read($id)
    {
        $info = $this->service->getById($id);
        if (!$info) {
            return json(['code' => 404, 'msg' => '文章不存在']);
        }
        
        // 字段映射：数据库cover_image -> 前端cover
        if (isset($info['cover_image'])) {
            $info['cover'] = $info['cover_image'];
        }
        
        return json(['code' => 200, 'msg' => 'success', 'data' => $info]);
    }

    /**
     * 新增文章
     */
    public function create(Request $request)
    {
        $data = $request->only(['category_id','title','cover','summary','content','author','is_top','status']);
        $validate = Validate::rule([
            'category_id' => 'require|number',
            'title' => 'require|max:128',
            'cover' => 'max:255',
            'summary' => 'max:255',
            'content' => 'require',
            'author' => 'max:64',
            'is_top' => 'in:0,1',
            'status' => 'in:0,1,2',
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 422, 'msg' => $validate->getError()]);
        }
        
        // 字段映射：前端cover -> 数据库cover_image
        if (isset($data['cover'])) {
            $data['cover_image'] = $data['cover'];
            unset($data['cover']);
        }
        
        // 不传递时间字段，让 Go 服务自动设置
        // Go 服务会在创建时自动设置 create_time 和 update_time
        
        $res = $this->service->create($data);
        return json(['code' => 200, 'msg' => '创建成功', 'data' => $res]);
    }

    /**
     * 编辑文章
     */
    public function update($id, Request $request)
    {
        $data = $request->only(['category_id','title','cover','summary','content','author','is_top','status']);
        $validate = Validate::rule([
            'category_id' => 'number',
            'title' => 'max:128',
            'cover' => 'max:255',
            'summary' => 'max:255',
            'author' => 'max:64',
            'is_top' => 'in:0,1',
            'status' => 'in:0,1,2',
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 422, 'msg' => $validate->getError()]);
        }
        
        // 字段映射：前端cover -> 数据库cover_image
        if (isset($data['cover'])) {
            $data['cover_image'] = $data['cover'];
            unset($data['cover']);
        }
        
        // 不传递时间字段，让 Go 服务自动设置
        // Go 服务会在更新时自动设置 update_time
        
        $res = $this->service->update($id, $data);
        if (!$res) {
            return json(['code' => 404, 'msg' => '文章不存在']);
        }
        return json(['code' => 200, 'msg' => '更新成功', 'data' => $res]);
    }

    /**
     * 删除文章
     */
    public function delete($id)
    {
        $res = $this->service->delete($id);
        if (!$res) {
            return json(['code' => 404, 'msg' => '文章不存在']);
        }
        return json(['code' => 200, 'msg' => '删除成功']);
    }
} 